package campshop.daos;

import java.sql.ResultSet;
import java.sql.SQLException;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.support.JdbcDaoSupport;

import campshop.models.UserInfo;

public class UserInfoDao extends JdbcDaoSupport{

	public long addUserInfo(UserInfo ui)
	{
		String sql = "insert into " +
				"tbl_char_static (cs_sCharName, cs_sPassword, cs_sProvince, cs_sSchool, cs_bIsSeller, cs_dCreateDate, cs_sPhoneNum)" +
				" values (?, ?, ?, ?, ?, ?, ?)";
		if(super.getJdbcTemplate().update(sql, ui.getsName(), ui.getsPassword(), ui.getsProvince(),
				ui.getsSchool(), ui.isbIsSeller()?1:0, ui.getdCreateDate(), ui.getsPhoneNum())>0){
			return super.getJdbcTemplate().queryForInt("select max(cs_uId) from tbl_char_static");
		}else return 0L;
	}
	
	public boolean delUserInfo(long uId)
	{
		String sql = "delete from tbl_char_static where cs_uId = ?";
		if(super.getJdbcTemplate().update(sql, uId)>0) return true;
		return false;
	}
	
	public boolean updateUserInfo(UserInfo ui) {
		String sql="update tbl_char_static " +
				"set cs_sCharName=?, cs_sPassword=?, cs_sProvince=?, cs_sSchool=?, cs_bIsSeller=?, cs_dCreateDate=?, cs_sPhoneNum=? " +
				"where cs_uId = ?";
		if(super.getJdbcTemplate().update(sql, ui.getsName(), ui.getsPassword(), ui.getsProvince(),
				ui.getsSchool(), ui.isbIsSeller()?1:0, ui.getdCreateDate(), ui.getsPhoneNum(), ui.getuId())>0){
			return true;
		}else return false;
	}
	
	public UserInfo getUserInfo(long uId)
	{
		String sql = "select * from tbl_char_static where cs_uId=" + uId;
		return (UserInfo)super.getJdbcTemplate().queryForObject(sql, new UserInfoRowMapper());
	}
	
	class UserInfoRowMapper implements RowMapper<UserInfo>{
		@Override
		public UserInfo mapRow(ResultSet rs, int rowNum) throws SQLException {
			UserInfo ui = new UserInfo();
			ui.setuId(rs.getLong("cs_uId"));
			ui.setsName(rs.getString("cs_sCharName"));
			ui.setsPassword(rs.getString("cs_sPassword"));
			ui.setsProvince(rs.getString("cs_sProvince"));
			ui.setsSchool(rs.getString("cs_sSchool"));
			ui.setbIsSeller(rs.getBoolean("cs_bIsSeller"));
			ui.setdCreateDate(rs.getDate("cs_dCreateDate"));
			ui.setsPhoneNum(rs.getString("cs_sPhoneNum"));
			return ui;
		}	
	}
}
